// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import ComponentBase from "../../../general/Script/component/ComponentBase";
import { BlockState, GameType } from "./content";
import DataMgr from "../../../general/Script/mgr/dataManager";
import GameMgr from "../../../general/Script/mgr/gameManager";






const {ccclass, property} = cc._decorator;

@ccclass
export default class BlockMap extends ComponentBase {


    map:string[][] = [];

    gameRow = 8;
    gameCol = 8;
    
    blockGame:cc.Node = null;
    touchNode:cc.Node = null;

    star:cc.Node = null;
    step:cc.Node = null;
    score:cc.Node = null;

    guanka:cc.Node = null;

    levelInfo:any[] = [];
    levelIndex:number = 0;
    levelType:GameType = GameType.normal;
    targets:number[] = [];
    // LIFE-CYCLE CALLBACKS:
    blockInfo:any = {}
    onLoad () {
        super.onLoad();
        for(let i  = 0;i< this.gameRow;i++){
            this.map[i] = [];
            for(let j = 0;j<this.gameCol;j++){
                this.map[i][j] = `${BlockState.none}_1`;
                let block = this.blockGame.children[i*this.gameCol+j];
                if(block){
                    
                    block.addComponent(cc.Button);
                    //添加触摸监听
                    block.on('click', this.blockTouch, this);
                    block.name = `${i}_${j}`;
                }else{
                    console.error('block is null',i,j);
                }
                
            }
        }

        
    }


    initMap(){
        for(let i  = 0;i< this.gameRow;i++){
            this.map[i] = [];
            for(let j = 0;j<this.gameCol;j++){
                this.map[i][j] = `${BlockState.none}_1`;
                let block = this.blockGame.children[i*this.gameCol+j];
                if(block){
                    
                    block.removeAllChildren(true);
                }else{
                    console.error('block is null',i,j);
                }
                
            }
        }
    }
    
    start () {
        const levelInfo = DataMgr.Ins().getLocalStorage('block_LevelInfo');
        console.log('levelInfo = ',levelInfo);
        if(levelInfo){
            this.levelInfo = levelInfo;
        }
        this.refreshLevel(0);
    }


    onDestroy(): void {
        super.onDestroy();

    }

    blockTouch(target){
        console.log('target = ',target.node.name);
        const node = target.node;
        const splice = node.name.split('_');
        if(this.blockInfo.state == BlockState.none){
            if(node.childrenCount>0){
                const b = node.children[0]
                b.removeFromParent(true);
                b.destroy();
            }
            this.map[parseInt(splice[0])][parseInt(splice[1])] = `${this.blockInfo.state}_${this.blockInfo.type}`;
        }else{
            if(node.childrenCount>0){
                const b = node.children[0]
                b.removeFromParent(true);
                b.destroy();
            }
            const block = cc.instantiate(this.touchNode);
            block.getComponent(cc.Button).interactable = true;
            node.addChild(block);
            block.removeComponent(cc.Button);
            block.x = 0;
            block.y = 0;
            this.map[parseInt(splice[0])][parseInt(splice[1])] = `${this.blockInfo.state}_${this.blockInfo.type}`;
        }
        console.log('map = ',splice,this.blockInfo.state,this.blockInfo.type,this.map[parseInt(splice[0])][parseInt(splice[1])]);
    }

    refreshMap(map){
        for(let i  = 0;i< this.gameRow;i++){
            for(let j = 0;j<this.gameCol;j++){
                const mapInfo = map[i][j];
                const types = mapInfo.split('_');
                const node = this.blockGame.getChildByName(`${i}_${j}`);
                if(node.childrenCount>0){
                    const b = node.children[0]
                    b.removeFromParent(true);
                    b.destroy();
                }
                if(types[0] != BlockState.none){
                    const block = cc.instantiate(this[`blockAdd_${types[0]}_${types[1]}`]);
                    node.addChild(block);
                    block.getComponent(cc.Button).interactable = true;
                    block.removeComponent(cc.Button);
                    block.x = 0;
                    block.y = 0;
                    this.map[i][j] = `${types[0]}_${types[1]}`;
                }
            }
        }
    }

    refreshLevel(step){
        this.levelIndex += step;
        this.guanka.getComponent(cc.Label).string = `${this.levelIndex}`;
        const mapInfo = this.levelInfo[this.levelIndex];
        if(mapInfo){
            if(mapInfo.map){
                this.refreshMap(this.strToMap(mapInfo.map));
            }else{
                console.error('mapInfo.map is null',this.levelIndex ,mapInfo);
            }
    
            console.log('mapInfo = ',mapInfo);
            const node = this[`gameType_${mapInfo.gameType}`];
            console.log('nodename = ',node.name);
            this.gameTypeCallBack(node.getComponent(cc.Button), mapInfo.gameType);

            switch(this.levelType){
                case GameType.score:
                    this.score.getChildByName('score').getComponent(cc.EditBox).string = mapInfo.targets[0];
                    
                    break;
                case GameType.step:
                    this.step.getChildByName('step').getComponent(cc.EditBox).string = mapInfo.targets[0];
                    break;
                case GameType.star:
                    this.star.getChildByName('type_0').getComponent(cc.EditBox).string = mapInfo.targets[0];
                    this.star.getChildByName('type_1').getComponent(cc.EditBox).string = mapInfo.targets[1];
                    this.star.getChildByName('type_2').getComponent(cc.EditBox).string = mapInfo.targets[2];
                    this.star.getChildByName('type_3').getComponent(cc.EditBox).string = mapInfo.targets[3];
    
                    break;
            }

        }else{
            this.initMap();
            for(let i = 1;i<4;i++){
                const node = this[`gameType_${i}`];
                if(node){
                    node.getComponent(cc.Button).interactable = true;
                }
            }
        }
       
    }
   
    blockAddCallBack(target, data1, data2){
       console.log('target, data', target, data1, data2);
        
       if(this.touchNode){
            this.touchNode.getComponent(cc.Button).interactable = true;
       }
       
       
       this.touchNode = target.node;
        
        
        this.blockInfo.state = data1;
        this.blockInfo.type = data2;
        this.touchNode.getComponent(cc.Button).interactable = false;



    }


    strToMap(mapStr){
        let mapStrArr = mapStr.split(':');
        let map = [];
        for(let i = 0;i<mapStrArr.length;i++){
            const mapRow = mapStrArr[i].split(',');
            map.push(mapRow);
        }
        return map;
    }

    mapToStr(map){
        let mapStrArr = [];

        for(let i = 0;i<map.length;i++){
            const mapRow = map[i].join(',');
            mapStrArr.push(mapRow);
        }
        return mapStrArr.join(':');
    }

    showMapCallBack(){
        console.log('this.map = ',this.map);

        switch(this.levelType){
            case GameType.score:
                const score = this.score.getChildByName('score').getComponent(cc.EditBox).string;
                this.targets = [Number(score)];
                break;
            case GameType.step:
                const step = this.step.getChildByName('step').getComponent(cc.EditBox).string;
                this.targets = [Number(step)];
                break;
            case GameType.star:
                const star_0 = this.star.getChildByName('type_0').getComponent(cc.EditBox).string;
                const star_1 = this.star.getChildByName('type_1').getComponent(cc.EditBox).string;
                const star_2 = this.star.getChildByName('type_2').getComponent(cc.EditBox).string;
                const star_3 = this.star.getChildByName('type_3').getComponent(cc.EditBox).string;

                this.targets = [Number(star_0),Number(star_1),Number(star_2),Number(star_3)];
                break;
        }




        const info = {
            gameType:this.levelType,
            map:this.mapToStr(this.map),
            targets:this.targets,
        }

        console.log('levelInfo = ',this.levelIndex,info);

        this.levelInfo[this.levelIndex] = info;
    }

    returnHomeCallBack(){   

        GameMgr.Ins().emit('overGame');
    }
    


    gameTypeCallBack(target:cc.Button,data){
        console.log('gameTypeCallBack',data);
        this.score.active = Number(data) === GameType.score;
        this.step.active = Number(data) === GameType.step;
        this.star.active = Number(data) === GameType.star;
        this.levelType = Number(data);
        for(let i = 1;i<4;i++){
            const node = this[`gameType_${i}`];
            if(node){
                node.getComponent(cc.Button).interactable = i != Number(data);
            }
        }


    }

    gameLevelCallBack(target:cc.Button,data){
        console.log('gameLevelCallBack',data);
        const step = Number(data);
        this.refreshLevel(step);
    }


    daochuCallBack(){
        const info = this.levelInfo;
        
        console.log(JSON.stringify(info));

        DataMgr.Ins().setLocalStorage('block_LevelInfo',info);

    }

}
